<template>
    <a-modal
        :title="isEdit ? '编辑' : '新增'"
        :open="props.open"
        @update:open="emit('update:open', $event)"
        @ok="handleSubmit"
        @cancel="handleCancel"
        :confirm-loading="confirmLoading"
    >
        <a-form ref="formRef" :model="formModel" :rules="rules" layout="vertical">
            <a-form-item label="用户名" name="username">
                <a-input v-model:value="formModel.username" placeholder="请输入用户名" allow-clear />
            </a-form-item>
            <a-form-item label="密码" name="password">
                <a-input v-model:value="formModel.password" type="password" placeholder="请输入密码" allow-clear />
            </a-form-item>
            <a-form-item label="昵称" name="nickname">
                <a-input v-model:value="formModel.nickname" placeholder="请输入昵称" allow-clear />
            </a-form-item>
            <a-form-item label="邮箱" name="email">
                <a-input v-model:value="formModel.email" type="email" placeholder="请输入邮箱" allow-clear />
            </a-form-item>
            <a-form-item label="手机号" name="phone">
                <a-input v-model:value="formModel.phone" placeholder="请输入分类描述" allow-clear />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup lang="ts">
import type { RuleObject } from "ant-design-vue/es/form";

import type { CreateSysUserDto, SysUserVo, UpdateSysUserDto } from "@/api/globals";

const props = defineProps<{
    open: boolean;
    record?: SysUserVo | null; // 回显数据，编辑时传入，新增时为 null 或 undefined
}>();

const emit = defineEmits<{
    (e: "update:open", value: boolean): void;
    (e: "success"): void;
}>();

// 表单引用
const formRef = ref();

// 表单数据
const formModel = reactive<Partial<UpdateSysUserDto & CreateSysUserDto>>({
    username: "",
    password: "",
    nickname: "",
    email: "",
    phone: "",
});

// 表单校验规则
const rules = reactive<Record<string, RuleObject | RuleObject[]>>({
    username: [{ required: true, message: "请输入用户名", whitespace: true, trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", whitespace: true, trigger: "blur" }],
    nickname: [{ required: true, message: "请输入昵称", whitespace: true, trigger: "blur" }],
    email: [{ required: true, message: "请输入邮箱", whitespace: true, trigger: "blur" }],
    phone: [{ required: true, message: "请输入手机号", whitespace: true, trigger: "blur" }]
});

// 是否为编辑模式
const isEdit = computed(() => !!props.record?.id);

// 确认加载状态
const confirmLoading = ref(false);

// 监听 open 变化，初始化表单
watch(
    () => [props.open, props.record],
    ([isOpen, record]) => {
        if (isOpen) {
            if (record) {
                // 编辑：回填数据
                Object.keys(formModel).forEach(key => {
                    (formModel as any)[key] = (props.record as any)[key];
                });
            } else {
                // 新增：清空表单
                Object.keys(formModel).forEach(key => {
                    (formModel as any)[key] = void 0;
                });
                formRef.value?.clearValidate(); // 重置表单验证状态
            }
        }
    },
    { immediate: true }
);

// 提交表单
const handleSubmit = async () => {
    try {
        const values = await formRef.value.validateFields();
        confirmLoading.value = true;

        if (isEdit.value) {
            // 调用编辑 API
            await Apis.SysUser.update({
                pathParams: { id: props.record!.id },
                data: values
            });
        } else {
            // 调用新增 API
            await Apis.SysUser.create({ data: values });
        }

        emit("success"); // 通知父组件刷新
        handleCancel(); // 关闭弹窗
    } catch (error) {
        console.error("表单提交失败:", error);
    } finally {
        confirmLoading.value = false;
    }
};

// 取消/关闭
const handleCancel = () => {};
</script>
